<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .status {
            font-weight: bold;
            margin-bottom: 10px;
        }
        .connected { color: green; }
        .disconnected { color: red; }
        .connecting { color: orange; }
        
        #messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
            background-color: #f9f9f9;
        }
        
        .message {
            margin-bottom: 5px;
            padding: 5px;
            border-radius: 3px;
        }
        .message.sent {
            background-color: #e3f2fd;
            text-align: right;
        }
        .message.received {
            background-color: #f3e5f5;
        }
        .message.system {
            background-color: #fff3e0;
            font-style: italic;
        }
        
        input[type="text"], input[type="number"] {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            box-sizing: border-box;
        }
        
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        .disconnect {
            background-color: #f44336;
        }
        
        .disconnect:hover {
            background-color: #da190b;
        }
    </style>
</head>
<body>
    <h1>WebSocket 测试页面</h1>
    
    <div class="container">
        <h3>连接配置</h3>
        <div>
            <label>WebSocket 地址:</label>
            <input type="text" id="wsUrl" value="ws://localhost:8282/ws/test_client_001" placeholder="ws://localhost:8282/ws/{clientId}">
        </div>
        <div>
            <label>客户端 ID:</label>
            <input type="text" id="clientId" value="test_client_001" placeholder="输入客户端标识">
        </div>
        <div class="status" id="status">状态: <span class="disconnected">未连接</span></div>
        <button id="connectBtn" onclick="connect()">连接</button>
        <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
    </div>

    <div class="container">
        <h3>消息</h3>
        <div id="messages"></div>
        <div>
            <input type="text" id="messageInput" placeholder="输入消息内容" onkeypress="handleKeyPress(event)">
            <button onclick="sendMessage()" id="sendBtn" disabled>发送消息</button>
        </div>
    </div>

    <div class="container">
        <h3>测试功能</h3>
        <div>
            <button onclick="sendOrderNotification()" id="orderBtn" disabled>模拟订单通知</button>
            <button onclick="sendSystemNotification()" id="systemBtn" disabled>模拟系统通知</button>
            <button onclick="requestOnlineCount()" id="countBtn" disabled>获取在线数量</button>
        </div>
        <div>
            <input type="text" id="orderId" placeholder="订单ID" value="TEST_ORDER_001">
            <input type="number" id="orderStatus" placeholder="订单状态(1-6)" value="2" min="1" max="6">
        </div>
    </div>

    <script>
        let ws = null;
        let isConnecting = false;

        function updateStatus(status, className) {
            const statusElement = document.getElementById('status');
            statusElement.innerHTML = `状态: <span class="${className}">${status}</span>`;
        }

        function updateButtonStates(connected) {
            document.getElementById('connectBtn').disabled = connected || isConnecting;
            document.getElementById('disconnectBtn').disabled = !connected;
            document.getElementById('sendBtn').disabled = !connected;
            document.getElementById('orderBtn').disabled = !connected;
            document.getElementById('systemBtn').disabled = !connected;
            document.getElementById('countBtn').disabled = !connected;
        }

        function addMessage(content, type = 'system') {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const timestamp = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `<small>[${timestamp}]</small> ${content}`;
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function connect() {
            if (isConnecting || (ws && ws.readyState === WebSocket.OPEN)) {
                return;
            }

            isConnecting = true;
            const url = document.getElementById('wsUrl').value;
            
            updateStatus('连接中...', 'connecting');
            updateButtonStates(false);
            
            try {
                ws = new WebSocket(url);
                
                ws.onopen = function(event) {
                    isConnecting = false;
                    updateStatus('已连接', 'connected');
                    updateButtonStates(true);
                    addMessage('WebSocket 连接已建立', 'system');
                };
                
                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        let content = '';
                        
                        switch(data.type) {
                            case 'order_status_update':
                                content = `订单状态更新: 订单 ${data.orderId} 状态变更为 ${data.statusText}(${data.status})`;
                                break;
                            case 'new_order':
                                content = `新订单通知: 订单号 ${data.order.id || '未知'}`;
                                break;
                            case 'system_notification':
                                content = `系统通知 [${data.level}]: ${data.title} - ${data.content}`;
                                break;
                            default:
                                content = data.message || event.data;
                        }
                        
                        addMessage(content, 'received');
                    } catch (e) {
                        addMessage(event.data, 'received');
                    }
                };
                
                ws.onclose = function(event) {
                    isConnecting = false;
                    updateStatus('连接已关闭', 'disconnected');
                    updateButtonStates(false);
                    addMessage(`连接已关闭 (代码: ${event.code}, 原因: ${event.reason || '未知'})`, 'system');
                };
                
                ws.onerror = function(error) {
                    isConnecting = false;
                    updateStatus('连接错误', 'disconnected');
                    updateButtonStates(false);
                    addMessage('WebSocket 连接错误', 'system');
                    console.error('WebSocket 错误:', error);
                };
                
            } catch (error) {
                isConnecting = false;
                updateStatus('连接失败', 'disconnected');
                updateButtonStates(false);
                addMessage('创建 WebSocket 连接失败: ' + error.message, 'system');
            }
        }

        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (message && ws && ws.readyState === WebSocket.OPEN) {
                ws.send(message);
                addMessage(message, 'sent');
                input.value = '';
            }
        }

        function sendOrderNotification() {
            const orderId = document.getElementById('orderId').value || 'TEST_ORDER_001';
            const status = document.getElementById('orderStatus').value || '2';
            
            const data = {
                type: 'test_order_notification',
                orderId: orderId,
                status: parseInt(status)
            };
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(data));
                addMessage(`发送订单通知测试: 订单${orderId}, 状态${status}`, 'sent');
            }
        }

        function sendSystemNotification() {
            const data = {
                type: 'test_system_notification',
                title: '系统维护通知',
                content: '系统将在今晚10点进行维护，预计持续1小时',
                level: 'warning'
            };
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(data));
                addMessage('发送系统通知测试', 'sent');
            }
        }

        function requestOnlineCount() {
            const data = {
                type: 'get_online_count'
            };
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(data));
                addMessage('请求在线用户数量', 'sent');
            }
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateButtonStates(false);
            
            // 自动更新URL中的客户端ID
            document.getElementById('clientId').addEventListener('input', function() {
                const clientId = this.value || 'test_client_001';
                document.getElementById('wsUrl').value = `ws://localhost:8282/ws/${clientId}`;
            });
        });
    </script>
</body>
</html>